package com.woniu.service.impl;

import com.woniu.entity.dto.UserStatisticsDTO;
import com.woniu.entity.dto.scoreLevelDTO;
import com.woniu.mapper.UserStatisticsMapper;
import com.woniu.service.UserStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserStatisticsServiceImpl implements UserStatisticsService {
    @Autowired
    private UserStatisticsMapper userStatisticsMapper;
    //查询最近7天的用户数据用在图标上
    @Override
    public UserStatisticsDTO getLast7DaysStatistics() {
        //生成最近7天的日期
        LocalDate today = LocalDate.now();
        ArrayList<String> dates = new ArrayList<String>();
        for(int i = 0; i < 7; i++){
            LocalDate date = today.minusDays(i);
            dates.add(date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
        Collections.reverse(dates);//反转集合
        //查询新增用户数据，转为map
        Map<String, Integer> newUserMap = userStatisticsMapper.countNewUserByDay().stream()
                .collect(Collectors.toMap(
                m -> (String) m.get("date"),
                m -> ((Number) m.get("count")).intValue()
        ));
        //查询活跃用户数据，转为map
        Map<String, Integer> activeUserMap = userStatisticsMapper.countActiveUserByDay().stream()
                .collect(Collectors.toMap(
                m -> (String) m.get("date"),
                m -> ((Number) m.get("count")).intValue()
        ));
        //组装数据，无数据补0
        List<Integer> newUserCounts = dates.stream()
                .map(date -> newUserMap.getOrDefault(date, 0))
                .collect(Collectors.toList());
        List<Integer> activeUserCounts = dates.stream()
                .map(date -> activeUserMap.getOrDefault(date, 0))
                .collect(Collectors.toList());

        UserStatisticsDTO userStatisticsDTO = new UserStatisticsDTO(dates, newUserCounts, activeUserCounts);
        return userStatisticsDTO;
    }
    //查询考试等级人数图标
    @Override
    public List<scoreLevelDTO> getScoreLevel(String contestId) {
       List<scoreLevelDTO> scoreLevel =userStatisticsMapper.getScoreLevel(contestId);
        return scoreLevel;
    }

}
